package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.CustIpAddressAttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Classname CustIpAddressAttrLinkHandler
 * @Description 客户自带广播IPv4地址段
 *    C类地址的计算规则： 2^(24-端口号)，所有ip地址计算结果相加
 * @Author zhang.song
 * @Date 2022-03-24 17:42
 */
@Service
@AttrHandler(CustIpAddressAttrHandler.class)
public class CustIpAddressAttrLinkHandler extends AbstractAttrLinkageHandler<AttrData> {


    @Override
    public void handle(KiteAttr attr, KiteInst inst, AttrData data) {
        if(Objects.isNull(attr) || KiteStringUtils.isEmpty(attr.getValue())) {
            return;
        }

        float num = 0;
        String[] ips = attr.getValue().split(SymbolConsts.COMMA);
        for (String ip : ips) {
            if(KiteStringUtils.contains(ip, "/")) {
                String portStr = ip.split("/")[1];
                if(KiteStringUtils.isNum(portStr)) {
                    Integer port = Integer.parseInt(portStr);
                    if(port <= 20) {
                        // <=20时，2^(24-20)=16，已满足条件，无需在计算其他值，防止计算数值过大
                        num += 16;
                        break;
                    } else if(port > 37) {
                        // 2^-14=1/16384，数值过小，基本无影响，防止计算数值过大，加固定值
                        num += 0.000062;
                    } else {
                        num += Math.pow(2, 24-port);
                    }
                }
            }
        }

        // 广播是否大于等于16C
        KiteAttr broadcastWith16CAttr = inst.getAttr("200002024");
        if(Objects.nonNull(broadcastWith16CAttr)) {
            if(num >= 16) {
                broadcastWith16CAttr.setValue("1_0000106");
                broadcastWith16CAttr.setValueDesc("是");
            } else {
                broadcastWith16CAttr.setValue("1_0000107");
                broadcastWith16CAttr.setValueDesc("否");
            }
            OperateInstAttrService operateInstAttrService = SpringUtil.getBean(OperateInstAttrService.class);
            operateInstAttrService.setAttrValue(inst, broadcastWith16CAttr.getFieldName(), broadcastWith16CAttr.getValue(), data.getSceneInstId(), null);
        }
    }

    @Override
    public void handleStyle(KiteAttr attr, KiteInst inst, AttrData data) {

    }
}
